package com.example.icedcap.topeka_fake.fragment;

import android.app.Activity;
import android.app.ActivityOptions;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.animation.FastOutSlowInInterpolator;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;

import com.example.icedcap.topeka_fake.R;
import com.example.icedcap.topeka_fake.activity.CategorySelectionActivity;
import com.example.icedcap.topeka_fake.adapter.AvatarAdapter;
import com.example.icedcap.topeka_fake.helper.PreferenceHelper;
import com.example.icedcap.topeka_fake.helper.TransitionHelper;
import com.example.icedcap.topeka_fake.model.Avatar;
import com.example.icedcap.topeka_fake.model.Player;
import com.example.icedcap.topeka_fake.widget.fab.DoneButton;

/**
 * Created by doushuqi on 15-7-11上午10:48.
 * Email:doushuqi0409@gmail.com
 */
public class SignInFragment extends Fragment {
    private static final String TAG = SignInFragment.class.getSimpleName();
    private static final String KEY_SELECT_AVATAR_INDEX = "selectAvatarIndex";
    private static final String ARG_EDIT = "EDIT";
    private GridView mAvatarsGrid;
    private Player mPlayer;

    private EditText mFirstName;
    private EditText mLastInitial;
    private Avatar mSelectAvatar = Avatar.ONE;
    private View mSelectAvatarView;

    private DoneButton mFabDone;
    private boolean mEdit;

    public static SignInFragment newInstance(boolean edit) {
        Bundle args = new Bundle();
        args.putBoolean(ARG_EDIT, edit);
        SignInFragment signInFragment = new SignInFragment();
        signInFragment.setArguments(args);
        return signInFragment;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putInt(KEY_SELECT_AVATAR_INDEX, mSelectAvatar.ordinal());
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        if (null != savedInstanceState) {
            int index = savedInstanceState.getInt(KEY_SELECT_AVATAR_INDEX);
            mSelectAvatar = Avatar.values()[index];
        }
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.fragment_sign_in, container, false);
        view.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                v.removeOnLayoutChangeListener(this);
                setUpGridView(getView());
            }
        });
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        assurePlayerInit();
        checkIsInEditMode();

        if (null == mPlayer || mEdit) {
            view.findViewById(R.id.empty).setVisibility(View.GONE);
            view.findViewById(R.id.content).setVisibility(View.VISIBLE);
            initContentView(view);
            initContent();
        } else {
            final Activity activity = getActivity();
            /*start activity*/
            CategorySelectionActivity.start(activity, mPlayer);
            activity.finish();
        }
        super.onViewCreated(view, savedInstanceState);
    }

    private void setUpGridView(View container) {
        mAvatarsGrid = (GridView)container.findViewById(R.id.avatars);
        mAvatarsGrid.setAdapter(new AvatarAdapter(getActivity()));
        mAvatarsGrid.setNumColumns(calculateSpanCount());
        mAvatarsGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mSelectAvatarView = view;
                mSelectAvatar = Avatar.values()[position];
            }
        });
        mAvatarsGrid.setItemChecked(mSelectAvatar.ordinal(), true);
    }

    private void initContentView(View view) {
        TextWatcher textWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        /*no-op*/
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (count > 0) {
                    mFabDone.setVisibility(View.VISIBLE);
                } else {
                    mFabDone.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
        /*no-op*/
            }
        };

        mFirstName = (EditText) view.findViewById(R.id.first_name);
        mFirstName.addTextChangedListener(textWatcher);
        mLastInitial = (EditText) view.findViewById(R.id.last_initial);
        mLastInitial.addTextChangedListener(textWatcher);
        mFabDone = (DoneButton) view.findViewById(R.id.done);
        mFabDone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //jump to an another activity or fragment
                switch (v.getId()) {
                    case (R.id.done):
                        savePlayer();
                        removeDoneButton(new Runnable() {
                            @Override
                            public void run() {
                                if (null == mSelectAvatarView) {
                                    performStartCategoryActivity(mAvatarsGrid.getChildAt(
                                            mSelectAvatar.ordinal()));
                                } else {
                                    performStartCategoryActivity(mSelectAvatarView);
                                }
                            }
                        });
                        break;

                    default:
                        throw new UnsupportedOperationException(
                                "The onClick method has not been implemented for " + getResources()
                                        .getResourceEntryName(v.getId())
                        );
                }

            }
        });
    }

    /**
     * done button clicked animate with start another activity or fragment.
     * @param runnable
     */
    private void removeDoneButton(@Nullable Runnable runnable) {
        mFabDone.animate()
                .scaleX(0f)
                .scaleY(0f)
                .setInterpolator(new FastOutSlowInInterpolator())
                .withEndAction(runnable)
                .start();
    }

    private void checkIsInEditMode() {
        final Bundle args = getArguments();
        if (null == args) {
            mEdit = false;
        } else {
            mEdit = args.getBoolean(ARG_EDIT, false);
        }
    }
    
    private void initContent() {
        assurePlayerInit();
        if (null != mPlayer) {
            mFirstName.setText(mPlayer.getFirstName());
            mLastInitial.setText(mPlayer.getLastInitial());
            mSelectAvatar = mPlayer.getAvatar();
        }
    }

    private void assurePlayerInit() {
        if (null == mPlayer) {
            mPlayer = PreferenceHelper.getPlayer(getActivity());
        }
    }

    private void savePlayer() {
        mPlayer = new Player(mFirstName.getText().toString(),
                mLastInitial.getText().toString(), mSelectAvatar);
        PreferenceHelper.writeToPreference(getActivity(), mPlayer);
    }

    private int calculateSpanCount() {
        final int avatarSize = getResources().getDimensionPixelSize(R.dimen.size_fab);
        final int avatarPadding = getResources().getDimensionPixelOffset(R.dimen.spacing_double);
        return mAvatarsGrid.getWidth() / (avatarSize + avatarPadding);
    }

    private void performStartCategoryActivity(View view) {
        final Activity activity = getActivity();
        final Pair[] sharedElements = TransitionHelper.createSafeTransitionParticipants(activity, true,
                new Pair<>(view, getString(R.string.transition_avatar)));
        ActivityOptions transition = ActivityOptions.makeSceneTransitionAnimation(activity, sharedElements);
        CategorySelectionActivity.start(activity, mPlayer, transition);
    }
}
